package org.example.ExperimentThree.ClientChart;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ChatClient {
    private String hostname;//主机号
    private int port;//端口号

    public ChatClient(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
    }

    public void start() {
//        使用Socket连接
        try (Socket clientSocket = new Socket(hostname, port);
             BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("聊天服务端连接");


            Thread inputThread = new Thread(new InputHandler(writer, scanner));
            inputThread.start();

            String serverMessage;
            while ((serverMessage = reader.readLine()) != null) {
                System.out.println(serverMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class InputHandler implements Runnable {
        private PrintWriter writer;
        private Scanner scanner;

        public InputHandler(PrintWriter writer, Scanner scanner) {
            this.writer = writer;
            this.scanner = scanner;
        }

        @Override
        public void run() {
            String message;
            while (true) {
                message = scanner.nextLine();
                writer.println(message);
                if (message.equalsIgnoreCase("quit")) {
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        String serverHostname = "localhost";
        int portNumber = 54239;

        ChatClient client = new ChatClient(serverHostname, portNumber);
        client.start();
    }
}

